<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>ajax</title>
</head>


<body>
    name:
    <input type="text" id="name"> age:
    <input type="text" id="age">
    <button onclick="add()">go</button>


    <table>
        <tbody>

        </tbody>
    </table>

    <script>
        function get() {
            let xhr = new XMLHttpRequest();
            xhr.open("get", "http://localhost:3000/users", true);
            xhr.onreadystatechange = function () {
                if (xhr.readyState == 4 && xhr.status == 200) {
                    let result = JSON.parse(xhr.responseText);
                    let table = document.getElementsByTagName("table")[0];
                    let tbody = table.getElementsByTagName("tbody")[0];
                    tbody.remove();
                    tbody = document.createElement("tbody");
                    result.forEach(element => {
                        let tr = document.createElement("tr");
                        let td1 = document.createElement("td");
                        let td2 = document.createElement("td");
                        let td3 = document.createElement("td");
                        td1.textContent = element.id;
                        td2.textContent = element.name;
                        td3.textContent = element.age;
                        tr.appendChild(td1);
                        tr.appendChild(td2);
                        tr.appendChild(td3);
                        tbody.appendChild(tr);
                    });
                    table.appendChild(tbody);
                }
            }
            xhr.send();
        }
        get();

        function add() {
            let xhr = new XMLHttpRequest();
            let url = "http://localhost:3000/users";
            let name = document.getElementById("name").value;
            let age = document.getElementById("age").value;

            let user = {};
            user.name = name;
            user.age = parseInt(age);

            xhr.onreadystatechange = function () {
                if (xhr.status == 201 && xhr.readyState == 4) {
                    get();
                }
            }
            xhr.open("POST", url);
            xhr.setRequestHeader("Content-type", "application/json");
            xhr.send(JSON.stringify(user));
        }
    </script>
</body>

</html>